package member

import (
	"context"
	"encoding/json"
	"fmt"
	model "micro-oauth/datamodels"
	"micro-oauth/datamodels/autherror"
	"micro-oauth/libs"
	"micro-oauth/repo"
	"micro-oauth/service/cache"
	"net/http"
)

type MemberServiceImpl struct {
	repoService  repo.ServiceInterface
	cacheService cache.CacheServiceInterface
	jwtSecret    string
}



func NewMemberService(repoService repo.ServiceInterface, cacheService cache.CacheServiceInterface, jwtSecret string) MemberServiceInterface {
	return &MemberServiceImpl{
		repoService:  repoService,
		cacheService: cacheService,
		jwtSecret:    jwtSecret,
	}
}

//用户注册
func (s *MemberServiceImpl) Register(user *model.User) (interface{}, autherror.HexError) {
	data := make(map[string]interface{})
	data["name"] = user.Name
	data["password"] = user.Password
	data["phone"] = user.Phone
	mjson,_ :=json.Marshal(data)
	mString :=string(mjson)
	userinfo,err := libs.HttpDo(http.MethodPost,"http://localhost:9090/user/userService/Register",mString,"")
	if err == nil {
		return nil, autherror.NotFound("can not found user")
	}
	return userinfo, nil
}

func (s *MemberServiceImpl) GetUserById(ctx context.Context, userId uint64) (*model.User, autherror.HexError) {
	pId := ctx.Value("partner_id").(uint64)
	scopeId, ok := ctx.Value("scope_id").(uint64)
	if !ok {
		scopeId = 0
	}
	user := s.repoService.GetUserById(userId)
	if user == nil {
		return nil, autherror.NotFound("can not found user")
	}
	if user.PartnerId != pId {
		return nil, autherror.PermissionDenied("no partner permission")
	}
	if user.ScopeId != scopeId {
		return nil, autherror.PermissionDenied("no scope permission")
	}
	return user, nil
}

//获取用户信息
func (s *MemberServiceImpl) GetUserInfo() (interface{}, autherror.HexError) {
	userinfo,err := libs.HttpDo(http.MethodGet,"http://localhost:9090/user/userService/GetUserInfo","","")
	fmt.Println("userinfo:",string(userinfo))
	if err != nil {
		return nil, autherror.NotFound("can not found user")
	}
	return userinfo, nil
}
